package ucap.com.lesanapp.activitys;

import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.bean.DateBean;
import ucap.com.lesanapp.bean.LeaderHeadContentBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;
import ucap.com.lesanapp.view.WebViewDialog;

public class LeaderListActivity extends AppCompatActivity {
    @Bind(R.id.iv_back)
    ImageView ivBack;
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.lv_content)
    ListView lvContent;
    @Bind(R.id.ll_leader_dates_loading)
    LinearLayout llLoading;
    @Bind(R.id.rl_content)
    RelativeLayout rlContent;
    @Bind(R.id.sRefresh)
    SwipeRefreshLayout sRefresh;
    ArrayList<DateBean.RowsBean> mListDate;
    private String uri;
    private String cacheName;
    private String name;
    private MyAdapter adapter;
    private int model;
    private int networkType;
    public String cid;
    public String sid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_leader_list);
        ButterKnife.bind(this);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        intiDate();

    }

    /**
     * 初始化
     */
    private void intiDate() {
        Intent intent = getIntent();
        name = intent.getStringExtra("name");
        uri = intent.getStringExtra("uri");
        cid = intent.getStringExtra("cid");
        sid = intent.getStringExtra("sid");
        cacheName = intent.getStringExtra("cacheName");
        tvTitle.setText(name);
        sRefresh.setVisibility(View.INVISIBLE);
        llLoading.setVisibility(View.VISIBLE);
        Log.i("leaderCid", "sid:" + sid);
        String cache = PrefUtils.getString(cacheName, "", this);
        if (!cache.isEmpty()) {
            analysisDate(cache);
            Log.i("leader_dates", "发现缓存。。");
        }
        getDateForService();
        getDeadLeaderContent();
        sRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getDateForService();
                sRefresh.setRefreshing(false);
            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //避免用户点击底部发生角标越界
                position -= 1;//加上头部角标
                if (position < mListDate.size() && position >= 0) {
                    DateBean.RowsBean item = adapter.getItem(position);
                    Intent intent = new Intent(LeaderListActivity.this, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
                    intent.putExtra("cid", cid);
                    startActivity(intent);
                }
            }
        });
        lvContent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
                vibrator.vibrate(60);
                position -= 1;//加上头部角标
                if (position < mListDate.size() && position >= 0) {
                    DateBean.RowsBean item = adapter.getItem(position);
                    WebViewDialog.showDialog(LeaderListActivity.this, item.getID(), item.getTITLE(), item.getCID());
                }
                return true;
            }
        });
    }


    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, this);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(this);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 获取服务器数据
     */
    public void getDateForService() {
        getType();
        HttpUtils utils = new HttpUtils();
        Log.i("leaderListUri", uri);
        utils.send(HttpMethod.GET, uri, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisDate(responseInfo.result);
                PrefUtils.putString(cacheName, responseInfo.result, getApplicationContext());
                Log.i("leaderDates", responseInfo.result);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
            }
        });
    }

    private void analysisDate(String result) {
        Gson gson = new Gson();
        DateBean date = gson.fromJson(result, DateBean.class);
        mListDate = (ArrayList<DateBean.RowsBean>) date.getRows();
        int number = mListDate.size();
        if (number > 0) {
            adapter = new MyAdapter();
            lvContent.setAdapter(adapter);
            sRefresh.setVisibility(View.VISIBLE);
            llLoading.setVisibility(View.GONE);

        } else {
            sRefresh.setVisibility(View.INVISIBLE);
            llLoading.setVisibility(View.INVISIBLE);
            TextView text = new TextView(getApplicationContext());
            text.setTextSize(20);
            text.setText("暂时没有数据!");
            text.setTextColor(Color.BLACK);
            rlContent.addView(text);
        }
        Log.i("dateSize", "总共数据:" + number + "条!");
    }

    /**
     * 获取领导介绍内容
     */
    public void getDeadLeaderContent() {
        HttpUtils http = new HttpUtils();
        http.send(HttpMethod.GET, Constants.LEADER_HEAD_CONTENT + "cid=" + sid, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                if (!responseInfo.result.isEmpty()) {
                    Log.i("LEADER_HEAD_CONTENT", "领导简介：" + responseInfo.result);
                    Gson gson = new Gson();
                    LeaderHeadContentBean leaderHeadContentBean = gson.fromJson(responseInfo.result, LeaderHeadContentBean.class);
                    List<LeaderHeadContentBean.RowsBean> rows = leaderHeadContentBean.getRows();
                    if (rows != null && rows.size() > 0) {
                        if (rows.get(0).getCONTENT().isEmpty())
                            return;
                        View view = View.inflate(LeaderListActivity.this, R.layout.head_leader_list, null);
                        ImageView ivPhoto = (ImageView) view.findViewById(R.id.iv_photo);
                        WebView web = (WebView) view.findViewById(R.id.web);
                        web.loadData(rows.get(0).getCONTENT(), "text/html;charset=UTF-8", null);//这种写法可以正确解码
                        BitmapUtils bitmapUtils = new BitmapUtils(LeaderListActivity.this);
                        bitmapUtils.display(ivPhoto, rows.get(0).getPATHURL());
                        lvContent.addHeaderView(view);
                    }
                }
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }


    class MyAdapter extends BaseAdapter {
        BitmapUtils bitmapUtils;

        MyAdapter() {
            bitmapUtils = new BitmapUtils(LeaderListActivity.this);
        }

        @Override
        public int getCount() {
            return mListDate.size();
        }

        @Override
        public DateBean.RowsBean getItem(int position) {
            return mListDate.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(LeaderListActivity.this, R.layout.item_date_content, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DateBean.RowsBean date = getItem(position);
            //判断服务器是否返回图片，没有就影藏图片控件
            if (!date.getPATHANDURL().isEmpty()) {
                //图文模式
                if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                    holder.ivPhoto.setVisibility(View.VISIBLE);
                    bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                } else if (model == SettingsModelState.MODEL_TEXT) {
                    //文本模式
                    holder.ivPhoto.setVisibility(View.GONE);
                } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                    //智能模式
                    if (networkType == ConnectivityManager.TYPE_WIFI) {
                        //wifi状态
                        holder.ivPhoto.setVisibility(View.VISIBLE);
                        bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                    } else {
                        holder.ivPhoto.setVisibility(View.GONE);
                    }
                }
            } else {
                holder.ivPhoto.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(date.getTITLE());
            holder.tvTime.setText(date.getTIME());
            holder.tvType.setText(date.getCHANNELNAME());
            return convertView;
        }
    }

    public class ViewHolder {
        @Bind(R.id.iv_news_photo)
        ImageView ivPhoto;
        @Bind(R.id.tv_news_title)
        TextView tvTitle;
        @Bind(R.id.tv_news_time)
        TextView tvTime;
        @Bind(R.id.tv_news_type)
        TextView tvType;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);//友盟统计
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
}
